import vue from '../main'
import store from '../store/index';
import { Loading, Notification  } from 'element-ui';
import { OBJ, viewer, zoomview } from './init'
import { PARAMS } from "./params"
import { showWaypoint, showWayPoints2 } from "./waypoint"
import { robotMarker } from './robot'
import { checkStr } from './methods'
/***
 * 建图函数
 */
export function displayMap(){
    return new Promise(function(resolve, reject){
        OBJ.topic.mapTopic.subscribe(function(msg){
            var imgMap = new ROS2D.ImageMap({
                image: msg.data,
                message: msg.info
            });
            
            //使用防抖更新地图base64数据
            store.commit("base64MapData", msg.data);
            console.log(msg);
            OBJ.mapMsg = msg;

            if(OBJ.imgMapStage){
                viewer.scene.removeAllChildren();
            }
            OBJ.imgMapStage = imgMap;
            viewer.scene.addChild(imgMap);
            let rmap = OBJ.mapInfo.windowWidth / imgMap.width;
            viewer.width = OBJ.mapInfo.windowWidth;
            viewer.height = imgMap.height * rmap;
            
            if(store.state.rosMode !== "gmapping"){
                viewer.scaleToDimensions(imgMap.width, imgMap.height);
                viewer.shift(imgMap.pose.position.x, imgMap.pose.position.y);
            }else{
                if(store.state.mappingFlag === false){
                    viewer.scaleToDimensions(imgMap.width, imgMap.height);
                    viewer.scene.x = OBJ.mapInfo.windowWidth / 2;
                    viewer.scene.y = OBJ.mapInfo.windowHeight / 2;
                    store.commit("mappingFlag", true);
                }
            }
            var mapPosition = {
                x: viewer.scene.x,
                y: viewer.scene.y
            }
            OBJ.mapXY = mapPosition;
            robotMarker();
            
            resolve("display map")
        })
    })
}

/**
 * 控制放大
 *  一秒切换logo过度效果
 * **/
export function zoomIn(scale) {
    let scaleNum = Number(store.state.scale);
    store.commit("zoomDisabled", 2)
    if (scale === 'zoomIn') {
        store.commit('setScale', scaleNum *= 1.2);
        if (scaleNum > 2.5) {
            store.commit('zoomDisabled', 0);
            return
        }
        showWayPoints2();
        robotMarker();
        zoomview.startZoom(viewer.scene.x + OBJ.robotStage.x, viewer.scene.y + OBJ.robotStage.y);
        zoomview.zoom(1.2);
    } else {
        store.commit('setScale', scaleNum *= 0.8);
        if (scaleNum < 0.32) {
            store.commit('zoomDisabled', 1);
            return
        }
        showWayPoints2();
        robotMarker();
        zoomview.startZoom(viewer.scene.x + OBJ.robotStage.x, viewer.scene.y + OBJ.robotStage.y);
        zoomview.zoom(0.8);
    }
};

/**
 * 显示建图
 * flag :true显示  :false隐藏
 * 如果用户引导程序未结束，显示新建站点
 * **/
export function showNewMap(flag=false){
    let guide = window.localStorage.getItem('guide');
    if(flag){
        store.commit("switchEditMapBtns", true);
        if(!guide){
            store.commit("guideIndex", 1);
        }
    }else{
        store.commit("switchEditMapBtns", false);
    }
}

/**
 * 点击新建地图
 * seq=1
 * frame_id=salm
 * **/
export function newMapping() {
    Loading.service({
        text: vue.$t("loading")
    });

    //发布启动建图话题,开始打点
    let message = {
        seq: 1,
        frame_id: 'slam'
    }
    var startMessage = new ROSLIB.Message(message);
    OBJ.topic.taskSwitchTopic.publish(startMessage)
    console.log('[INFO]Start mapping');
    Loading.service().close();
};

/**
 * 点击继续建图
 * seq=2
 * frame_id=salm
 * **/
export function continueMapping() {
    if (store.state.rosMode === PARAMS.rosMode.gmapping) {
        Notification({
            title: vue.$t("titles.warning"),
            message: vue.$t("messages.nowMapping"),
            type: 'warning',
            position: 'top-left',
            offset: 100
        });
        return;
    }
    
    Loading.service({
        text: vue.$t("loading")
    })

    //发布启动建图话题,开始打点
    let goonMsg = {
        seq: 2,
        frame_id: 'slam'
    }
    var goonMessage = new ROSLIB.Message(goonMsg)
    OBJ.topic.taskSwitchTopic.publish(goonMessage);
    console.log('[INFO]continue mapping');
    Loading.service().close();
};

/**
 * 保存并继续建图
 * **/
export function submitSaveMapContinue(mapName){
    let mapNameStr = "";
    if(mapName){
        if (!checkStr(mapName)) {
            Notification({
                title: vue.$t("titles.warning"),
                message: vue.$t("messages.theNameUnavailable"),
                type: 'warning',
                position: 'top-left',
                offset: 100
            });
            return;
        }
        mapNameStr = "_" + mapName;
    }else{
        mapNameStr = "";
    }
    
    Loading.service({
        text: vue.$t("inTheSave")
    });
    //保存地图
    let saveMsg = {
        seq: 1,
        frame_id: `save_map${mapNameStr}`
    }

    OBJ.topic.taskSwitchTopic.publish(new ROSLIB.Message(saveMsg));
    setTimeout(function(){
        Loading.service().close();
        Notification({
            title: vue.$t("titles.success"),
            message: vue.$t("messages.saveSuccess"),
            type: 'success',
            position: 'top-left',
            offset: 100
        });
    }, 2000)
};

/**
 * 保存并关闭建图
 * 保存：seq=1,frame_id=map
 * 关闭建图:seq=0,frame_id=slam
 * **/
export function submitSaveMapBtn(mapName) {
    let mapNameStr = "";
    if(mapName){
        if (!checkStr(mapName)) {
            Notification({
                title: vue.$t("titles.warning"),
                message: vue.$t("messages.theNameUnavailable"),
                type: 'warning',
                position: 'top-left',
                offset: 100
            });
            return;
        }
        mapNameStr = "_" + mapName;
    }else{
        mapNameStr = "";
    }
    
    //引导流程为建图
    window.localStorage.setItem('guideName', 'map');

    Loading.service({
        text: vue.$t("inTheSave")
    });
    //保存地图
    let saveMsg = {
        seq: 1,
        frame_id: `save_map${mapNameStr}`
    }
    //关闭建图
    let closeMsg = {
        seq: 0,
        frame_id: 'slam'
    }
    OBJ.topic.taskSwitchTopic.publish(new ROSLIB.Message(saveMsg));

    //关闭建图
    setTimeout(function () {
        var closeMessage = new ROSLIB.Message(closeMsg);
        OBJ.topic.taskSwitchTopic.publish(closeMessage);
        setTimeout(function () {
            //引导流程为建图
            window.localStorage.setItem('guideName', 'map');
            //关闭建图模态框
            showNewMap(false);

            Loading.service().close();

            //关闭建图模态框
            showNewMap(false);

            //显示新建站点模态框
            let guide = window.localStorage.getItem('guide');
            if(!guide){
                showWaypoint(true);
            }

            Notification({
                title: vue.$t("titles.success"),
                message: vue.$t("messages.saveSuccess"),
                type: 'success',
                position: 'top-left',
                offset: 100
            });
        }, 8000)
    }, 1000)
};


/**
 * 显示上传地图
 * flag :true显示  :false隐藏
 * 如果用户引导程序未结束，显示新建站点
 * **/
export function showUploadMap(flag){
    if(flag){
        store.commit("switchUploadMap", true);
    }else{
        store.commit("switchUploadMap", false);
    }
}

/**
 * 显示下载地图
 * flag :true显示  :false隐藏
 * 如果用户引导程序未结束，显示新建站点
 * **/
export function showDownloadMap(flag){
    if(flag){
        store.commit("switchDownloadMap", true);
    }else{
        store.commit("switchDownloadMap", false);
    }
}

/**
 *上传图片 
 *params
 *  *base64     -   map base64data
 *  *type       -   map/mapEdit
 *  *width      -   map width
 *  *height     -   map height
 * **/
export function uploadMap(params){
    let msg = new ROSLIB.Message({
        header: {
            // seq: OBJ.mapMsg.header.seq,
            frame_id: "map"
        },
        info:{
            resolution: OBJ.mapMsg.info.resolution,
            width: OBJ.mapMsg.info.width,
            height: OBJ.mapMsg.info.height,
            origin: {
                orientation: {
                    x: OBJ.mapMsg.info.origin.orientation.x,
                    y: OBJ.mapMsg.info.origin.orientation.y,
                    z: OBJ.mapMsg.info.origin.orientation.z,
                    w: OBJ.mapMsg.info.origin.orientation.w,
                },
                position: {
                    x: OBJ.mapMsg.info.origin.position.x,
                    y: OBJ.mapMsg.info.origin.position.y,
                    z: OBJ.mapMsg.info.origin.position.z,
                }
            }
        },
        data: params.base64
    })
    console.log(params.base64)
    if(params.type == "map"){
        OBJ.topic.uploadMapTopic.publish(msg);
    }else if(params.type == "map_edit"){
        OBJ.topic.uploadMapEditTopic.publish(msg)
    }
}

/**
 * 订阅map_stream
 * msg
 *  *data   -   base64
 * **/
export function subMapEdit(){
    return new Promise(function(resolve, reject){
        OBJ.topic.mapEditTopic.subscribe(function(msg){
            resolve("display map_edit")
            OBJ.topic.mapTopic.unsubscribe();
            console.log(msg)
            return msg.data
        })
    })
}